#include "rtc.h"

RTC_HandleTypeDef hrtc;
RTC_TimeTypeDef sTime = {0};
RTC_DateTypeDef sDate = {0};

void MX_RTC_Init(void)
{
    hrtc.Instance = RTC;
    hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
    hrtc.Init.AsynchPrediv = 127;
    hrtc.Init.SynchPrediv = 255;
    hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
    hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
    hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;

    if (HAL_RTC_Init(&hrtc) != HAL_OK)
    {
        Error_Handler();
    }

    /**
     * initialize RTC and set the Time and Date
     */
    if (HAL_RTC_GetState(&hrtc) == HAL_RTC_STATE_RESET)
    {
        sTime.Hours = 0x13;
        sTime.Minutes = 0x0C;
        sTime.Seconds = 0x47;
        sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
        sTime.StoreOperation = RTC_STOREOPERATION_RESET;
        if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK)
        {
            Error_Handler();
        }
        sDate.WeekDay = RTC_WEEKDAY_FRIDAY;
        sDate.Month = RTC_MONTH_SEPTEMBER;
        sDate.Date = 0x1B;
        sDate.Year = 0x18;
        if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BCD) != HAL_OK)
        {
            Error_Handler();
        }
    }

    /**
     * Enable the TimeStamp
     */
    if (HAL_RTCEx_SetTimeStamp(&hrtc, RTC_TIMESTAMPEDGE_RISING, RTC_TIMESTAMPPIN_PC13) != HAL_OK)
    {
        Error_Handler();
    }
}

uint32_t rtc_GetCounter(void)
{
    return (uint32_t)(&hrtc.Instance->TR);
}


/**
 * @brief HAL_RTC_MspInit
 * @param hrtc - RTC_HandleTypeDef
 * @retval NULL
 */
// void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc)
//{
//     if (hrtc->Instance == RTC) {
//         __HAL_RCC_RTC_ENABLE();     // 开启RTC时钟
//     }
// }